/**
 * 工作流会签加签
 */

import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Col, Form, Input, message, Row, Select, Spin, TreeSelect } from 'antd';
import { Ref, useEffect, useRef } from 'react';
import pageStyles from '@/common/pageLayout.less';
import {
  getFlowOrgTreeByOrgIDService,
  getUserDataList,
} from '@/services/BaseLayout';
import { commonDeptGetUser, getDeptPosTreeIcon } from '@/utils';
import MyIcon from '@/components/MyIcon';
import { addMulitiService } from '../services';

export const WorkflowAddSignModal: React.FC<WorkflowOtherFuncAPI.IWorkflowAddSignModal> = ({
  onClose,
  openVisible,
  requestController,
  selectRowsInfo,
  reloadCallback,
  getPostDataParams,
}) => {
  const [AddSignForm] = Form.useForm(); //表单 form

  /**
   * modal ref
   */
  const flowAddSignModalRef: Ref<IOneModalRef> = useRef(null);

  /**
   * 关闭弹窗
   */
  const onCloseModal = () => {
    if (flowAddSignModalRef) {
      if (flowAddSignModalRef.current) {
        if (flowAddSignModalRef.current.onModalCancel) {
          flowAddSignModalRef.current.onModalCancel();
        }
      }
    }
  };

  /**获取组织机构树 接口 */
  const {
    getFlowOrgTreeRun,
    getFlowOrgTreeLoading,
    getFlowOrgList,
  } = getFlowOrgTreeByOrgIDService();
  const { getUserRun, getUserLoading, getUserList } = getUserDataList(
    (res: any) => {
      if (!(res && res?.msgFlag)) {
        message.error(res?.msg);
      }
    },
  );

  // 处理树数据
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      return {
        ...item,
        title: (
          <div>
            {getDeptPosTreeIcon(String(item?.textType))}
            {item?.text}
          </div>
        ),
        searchtitle: item?.text,
        key: item?.id,
        value: item?.id,
        children:
          item?.children && item?.children?.length > 0
            ? orgTreeData(item?.children)
            : null,
        disabled: item?.textType == '2' ? false : true,
      };
    });
  };

  // 点击左侧树结构
  const onTreeSelect = (selectedKeys: any, selectedNodes: any) => {
    AddSignForm?.setFieldsValue({ ownerID: null });
    let userListPayload = commonDeptGetUser([selectedNodes]);
    AddSignForm?.setFieldsValue({
      assigneeDepartmentID: selectedNodes?.attributes?.departmentID,
      assigneeCompanyID: selectedNodes?.attributes?.companyID,
    });
    getUserRun(userListPayload);
  };

  /**
   * 初始化获取组织机构树
   */
  useEffect(() => {
    if (
      openVisible &&
      getPostDataParams &&
      JSON.stringify(getPostDataParams) != '{}'
    ) {
      getFlowOrgTreeRun(getPostDataParams);
    }
  }, [openVisible, getPostDataParams]);

  /**
   * 接口回调
   */
  const addMulitiCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      onCloseModal();
      reloadCallback();
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入会签接口
   */
  const { addMulitiLoading, addMulitiRun } = addMulitiService(
    addMulitiCallback,
    requestController,
  );

  /**
   * 保存
   */
  const onOk = () => {
    AddSignForm?.validateFields()?.then((values: any) => {
      let params: Record<string, any> = {
        id: selectRowsInfo.id,
        procInstID: selectRowsInfo.procInstID,
        taskDefKey: selectRowsInfo.taskDefKey,
        orderID: selectRowsInfo.orderID,
        taskIsSign: '1', //【是否会签(0: 普通任务 1: 会签任务)】
        ...values,
      };
      addMulitiRun(params);
    });
  };

  return (
    <>
      <OneModal
        open={true}
        // getContainer={false}
        ref={flowAddSignModalRef}
        title={'会签加签'}
        width={document.body.clientWidth * 0.3}
        onCancel={onClose}
        bodyStyle={{
          padding: '5px 10px',
        }}
        centered
        onOk={onOk}
        confirmLoading={getFlowOrgTreeLoading || addMulitiLoading}
      >
        <Spin spinning={getFlowOrgTreeLoading || addMulitiLoading}>
          <div className={pageStyles['fromView-styles']}>
            <Form labelAlign="right" form={AddSignForm}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    label={'办理岗位'}
                    name="assigneePositionID"
                    rules={[
                      {
                        required: true,
                        message: '请选择办理岗位',
                      },
                    ]}
                  >
                    <TreeSelect
                      placeholder={'请选择办理岗位'}
                      showSearch
                      allowClear
                      treeNodeFilterProp={'searchtitle'}
                      treeData={orgTreeData(getFlowOrgList)}
                      onSelect={onTreeSelect}
                    />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label={'办理人'}
                    name="assigneeID"
                    rules={[
                      {
                        required: true,
                        message: '请选择办理人',
                      },
                    ]}
                  >
                    <Select
                      placeholder={'请选择办理人'}
                      loading={getUserLoading}
                      allowClear
                      showSearch
                      optionFilterProp={'searchtitle'}
                    >
                      {getUserList && getUserList?.length > 0 ? (
                        <>
                          {getUserList?.map((item: any) => {
                            return (
                              <Select.Option
                                // disabled={
                                //   item?.id == getUserID() ? true : false
                                // }
                                value={item?.id}
                                key={item?.id}
                                searchtitle={item?.realName}
                              >
                                <MyIcon
                                  style={{ marginRight: 5 }}
                                  type="icon-lianxiren"
                                />
                                {item?.realName}
                              </Select.Option>
                            );
                          })}
                        </>
                      ) : (
                        <></>
                      )}
                    </Select>
                  </Form.Item>

                  <Form.Item
                    style={{
                      display: 'none',
                    }}
                    name="assigneeDepartmentID"
                    label=""
                  >
                    <Input hidden />
                  </Form.Item>
                  <Form.Item
                    style={{
                      display: 'none',
                    }}
                    name="assigneeCompanyID"
                    label=""
                  >
                    <Input hidden />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
